package ch.zbw.timeline.presentation.component;

import java.awt.BorderLayout;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.table.DefaultTableModel;

import ch.zbw.timeline.domain.Employee;
import ch.zbw.timeline.domain.LogEntry;
import ch.zbw.timeline.presentation.helper.Formatter;

/**
 * Panel for the log entries
 * 
 * @author Daniel Stefanovic
 * @version 18.01.2012
 * 
 */
public class LogPanel extends JPanel {

	private JTable logTable = new JTable();
	private DefaultTableModel tableModel;

	/**
	 * Constructor
	 */
	public LogPanel() {
		this.setLayout(new BorderLayout());
		this.add(createTable());
	}

	/**
	 * Create the table for the entries
	 * 
	 * @return table
	 */
	private JScrollPane createTable() {

		String[] columnNames = { "Zeitpunkt", "Typ", "Benutzer", "Beschreibung" };
		
		tableModel = new DefaultTableModel(new Object[][] {}, columnNames) {
			// cells are not editable
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return false;
			}
		};

		logTable = new JTable(tableModel);
		JScrollPane scroll = new JScrollPane(logTable);

		Border loweredEtched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
		scroll.setBorder(BorderFactory.createTitledBorder(loweredEtched, "Log"));

		return scroll;
	}
	
	/**
	 * Fills the panel with the list of processes 
	 * 
	 * @param logEntries list of all log entries
	 */
	public void loadData(List<LogEntry> logEntries) {
		
		String displayName = "";
		Employee employee = null;
		
		// clear tableModel
		int row = tableModel.getRowCount();
		for (int counter = (row) - 1; counter > -1; counter--) {
			tableModel.removeRow(counter);
		}

		// fill tableModel
		for (LogEntry l : logEntries) {
			String timestamp = Formatter.INSTANCE.formatTimestamp(l.getRegistredOn());
			
			if(l.getEmployee() != null){
				employee = l.getEmployee();
				displayName = employee.getUserName() + " (" + employee.getFirstName() + " " + employee.getLastName() + ")";
				tableModel.addRow(new Object[] { timestamp, l.getLogTypeString(), displayName, l.getDescription() });
			}
			else{
				tableModel.addRow(new Object[] { timestamp, l.getLogTypeString(), "", l.getDescription() });
			}
		}
	}
}
